// Copyright (c)  YISH. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

using System;
using System.Collections;
using System.Collections.Generic;

namespace NSQL.Expressions
{
    public class ExpressionCollector : AbstractExpressionVisitor, IReadOnlyList<IExpression>
    {
        private readonly IList<IExpression> _list;

        public ExpressionCollector(IExpression expression)
        {
            if (expression == null)
            {
                _list = Array.Empty<IExpression>();
            }
            else
            {
                _list = new List<IExpression>();
                Init(expression);
            }
        }

        private void Init(IExpression expression)
        {
            VisitChildren(expression);
        }
        
        protected override void VisitChildren(IExpression expression)
        {
            if (expression is null) return;
            _list.Add(expression);
            base.VisitChildren(expression);
        }

        public IEnumerator<IExpression> GetEnumerator() => _list.GetEnumerator();

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        public int Count => _list.Count;

        public IExpression this[int index] => _list[index];
    }
}